import watcher from "./observer/watcher";
import { patch } from "./vnode/patch";

export function mounteComponent(vm, el) {
  callHook(vm, "beforeMount");
  let updataComponent = () => {
    vm._updata(vm._render()); //1.vm._render 将reder函数变成vnode 2. vm._updata 把VNode变成真实dom放在原型上
  };
  new watcher(
    vm,
    updataComponent,
    () => {
      callHook(vm, "updated");
    },
    true
  );
  callHook(vm, "mounted");
}
export function lifecycleMixin(Vue) {
  Vue.prototype._updata = function (vnode) {
    let vm = this;
    //旧的dom 新的 vnode
    //区分是首次还是更新
    let prevVnode = vm._vnode; //首次更新为null 后面更新就传入虚拟dom更新 实现diff对比
    if (!prevVnode) {
      vm.$el = patch(vm.$el, vnode);
      vm._vnode = vnode;
    } else {
      patch(prevVnode, vnode);
    }
  };
}
//生命周期调用
export function callHook(vm, hook) {
  const handlers = vm.$options[hook];
  if (handlers) {
    for (let index = 0; index < handlers.length; index++) {
      handlers[index].call(vm);
    }
  }
}
